package com.zlq.work08;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class ClassPathXmlApplicationContext implements ApplicationContext {
    private Map<String, Object> ioc = new HashMap<String, Object>();

    public ClassPathXmlApplicationContext(String path) {
        try {
            //1. 将xxx.xml转成Document对象
            SAXReader reader = new SAXReader();
            Document document = reader.read("./src/main/resources/" + path);
            //2. dog4j 解析 XML
            //2.1 首先获取根节点对象<beans>
            Element root = document.getRootElement();
            //2.2 迭代获取子节点对象<bean>
            //获取一个迭代器
            Iterator<Element> iterator = root.elementIterator();
            //循环
            while(iterator.hasNext()){//若迭代器中有下一个
                Element element = iterator.next();
                //2.2.1 获取key，即bean中的id属性值
                String id = element.attributeValue("id");//把属性名id传进去
                System.out.println(id);
                //2.2.2 获取全类名，即bean中的class属性值
                String className = element.attributeValue("class");//把属性名class传进去
                System.out.println(id + ":" + className);

                //2.2.3 获去value，即通过全类名，通过反射机制调用无参构造函数创建对象
                //2.2.3.1 通过反射机制获取class对象
                Class clazz = Class.forName(className);
                /*
                //2.2.3.2 获取无参构造方法对象
                Constructor constructor = clazz.getConstructor();
                //2.2.3.3 创建目标对象
                Object object = constructor.newInstance();
                */
                //2.2.3.2 调用无参构造函数创建目标对象
                //如果使用无参数构造方法创建对象，可简化为：Class对象的newInstance方法，即Class对象.newInstance()（常用此操作）
                Object object = clazz.newInstance();

                //2.2.4 给目标对象赋值
                Iterator<Element> beanIter = element.elementIterator();
                while(beanIter.hasNext()){
                    Element property = beanIter.next();
                    //获取property中name、value、ref的值
                    String name = property.attributeValue("name");
                    String valueStr = property.attributeValue("value");
                    String ref = property.attributeValue("ref");

                    //通过反射调用目标对象的set方法完成对对象的赋值
                    //字符串拼接得到set方法名
                    String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
                    System.out.println("method name = " + methodName);
                    //获取成员变量对象
                    Field field = clazz.getDeclaredField(name);// 获取private修饰的成员变量
                    //第一个参数是set方法名，第二个参数是set方法的参数类型
                    Method method = clazz.getDeclaredMethod(methodName, field.getType());
                    if(ref == null){//<property name="" value=""/>
                        //根据成员变量的数据类型将 valueStr 进行转换
                        Object value = null;
                        if(field.getType().getName() == "long"){
                            value = Long.parseLong(valueStr);//包装类方法将String类型转成long类型
                        }
                        if(field.getType().getName() == "java.lang.String"){
                            value = valueStr;
                        }
                        if(field.getType().getName() == "int"){
                            value = Integer.parseInt(valueStr);
                        }
                        //执行set方法
                        method.invoke(object, value);
                    }else{//<property name="" ref=""/> 依赖注入DI
                        Object refValue = ioc.get(ref);
                        //执行set方法
                        method.invoke(object, refValue);
                    }
                }

                //2.2.5 key和value存入map集合
                ioc.put(id, object);
            }
            //System.out.println(ioc);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        System.out.println(ioc);

    }

    public Object getBean(String id) {
        return ioc.get(id);
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        MoAttack moAttack = (MoAttack) applicationContext.getBean("moAttack");
        moAttack.cityGateAsk();

//        Student student = (Student) applicationContext.getBean("student");

    }
}



























